﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orange.Mvc4App.Models;
using System.IO;
using System.Web;

namespace Orange.Mvc4App.Services
{
    public interface IChargeService
    {
        void ReadFile(HttpPostedFileBase file);
        IList<Charge> GetList(bool? isWater);
    }

    public class ChargeService : BaseService, IChargeService
    {

        public void ReadFile(HttpPostedFileBase file)
        {
            //int length = file.ContentLength;
            //byte[] buffer = new byte[length - 1];
            //file.InputStream.Read(buffer, 0, length);
            //string path = "";
            List<Charge> list = new List<Charge>();
            //using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
            //{
            using (StreamReader sr = new StreamReader(file.InputStream))
            {
                int line = 1;
                while (!sr.EndOfStream)
                {
                    string Line = sr.ReadLine();
                    string[] infos = Line.Split(',');

                    if ((line++) % 2 == 1)
                    {
                        list.Add(new Charge
                        {
                            Type = "电费",
                            Date = Convert.ToDateTime(infos[0]),
                            Amount = Convert.ToDecimal(infos[2]),
                            Price = Convert.ToDecimal(infos[4])
                        });
                    }
                    else
                    {
                        list.Add(new Charge
                        {
                            Type = "水费",
                            Date = Convert.ToDateTime(infos[0]),
                            Amount = Convert.ToDecimal(infos[1]),
                            Price = Convert.ToDecimal(infos[3])
                        });
                    }
                }
            }
            //}
            foreach (var item in list)
            {
                db.Charges.Add(item);
            }
            db.SaveChanges();
        }

        public IList<Charge> GetList(bool? isWater)
        {
            if (isWater == null)
            {
                return db.Charges.ToList();
            }
            else
            {
                if ((bool)isWater)
                {
                    return db.Charges.Where(c => c.Type == "水费").ToList();
                }
                else
                {
                    return db.Charges.Where(c => c.Type == "电费").ToList();
                }
            }

        }
    }
}
